<template>
  <div class="common-project-container">
    <SectionTitle title="报销项目" style="margin: 32px 0 16px;">
      <div class="total-amount-price">
        <img :src="AmountIcon" alt="">总报销金额：
        <span class="price">{{ getTotalReimbursementAmount }}</span>
      </div>
      <div v-if="isEdit" class="options-btn-group">
        <PlainCreateBtn @click="handleAdd">添加</PlainCreateBtn>
      </div>
    </SectionTitle>
    <dynamicEditTable
      ref="dynamicEditTableRef"
      v-model="commonProjectList"
      :list-setting="listSetting"
      :list-data="commonProjectList"
      :is-edit="isEdit"
      :show-delete-btn="isEdit"
      :show-serial="false"
      :fixed="false"
      :show-add-btn="false"
      :show-copy-btn="isEdit"
      :extend-btn="extendBtnKey"
      @extendEvent="extendEvent"
      @handelClickEdit="handelClickEditTag"
    />
    <EditTagModule ref="editTagModuleRef" :edit-tag-api="editReimbursementTag" :extend-params="editTagParams" :module-type="TAG_MODULES.PROCESS" @callback="editTagCallback" />
  </div>
</template>

<script>
// components
import SectionTitle from '@/components/Title';
import dynamicEditTable from '@/components/Common/dynamicEditTable';
import EditTagModule from '@/components/SupplierComponent/currentWidthdrawInfo/editTag';
// img
import AmountIcon from '@/assets/chargeOffDetail/incomeAmount.png';
import { TAG_MODULES } from '@/utils/const';
import { getTagAll } from '@/api/config';
import { editReimbursementTag } from '@/api/reimbursement';
import { hasRouteAuth } from '@/utils/permission';

export default {
  components: { SectionTitle, dynamicEditTable, EditTagModule },
  model: {
    prop: 'totalReimbursementAmount',
    event: 'change'
  },
  props: {
    totalReimbursementAmount: {
      type: Number | String,
      default: null
    },
    isEdit: {
      type: Boolean,
      default: true
    },
    showExtendBtn: {
      type: Boolean,
      default: false
    },
    isCurrentVersion: {// 是否当前版本
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      TAG_MODULES,
      AmountIcon,
      commonProjectList: [{
        project: '',
        amount: '',
        desc: ''
      }],
      tagTreeList: [],
      editTagParams: {}
    };
  },
  computed: {
    projectTypes() {
      return [
        { id: 1, name: '商务宴请费' },
        { id: 2, name: '业务宣传费' },
        { id: 3, name: '福利费' },
        { id: 4, name: '办公费' },
        { id: 5, name: '快递费' },
        { id: 6, name: '外出打车费' },
        { id: 7, name: '加班打车费' },
        { id: 8, name: '其他费用' }
      ];
    },
    listSetting() {
      const settingArr = [
        {
          label: '报销金额(元)',
          type: 'inputNumber',
          width: '150px',
          maxnumber: 999999999,
          isRequired: true,
          keyword: 'amount',
          isPositiveNumber: true,
          placeholder: '请输入'
        }, {
          label: '报销说明',
          type: 'inputText',
          width: '400px',
          maxlength: 500,
          isRequired: true,
          keyword: 'desc',
          placeholder: '费用详细阐述，包括不限于原因，用途'
        }, {
          label: '标签',
          type: 'tagSelect',
          width: '240px',
          keyword: 'tag',
          isShowEditBtn: hasRouteAuth('crm:reimbursement:tagEdit') && this.isCurrentVersion,
          moduleType: this.TAG_MODULES.PROCESS,
          defaultTagList: this.tagTreeList
        }
      ];
      if (this.isEdit) {
        settingArr.unshift({
          label: '报销项目',
          type: 'select',
          keyword: 'project',
          isRequired: true,
          width: '180px',
          placeholder: '请选择',
          options: this.projectTypes
        });
      } else {
        settingArr.unshift({
          label: '报销项目',
          type: 'inputText',
          width: '180px',
          keyword: 'projectName'
        });
      }
      return settingArr;
    },
    getTotalReimbursementAmount() {
      if (this.totalReimbursementAmount || this.totalReimbursementAmount === 0) {
        return this.totalReimbursementAmount;
      }
      return '--';
    },
    extendBtnKey() {
      return this.showExtendBtn ? 'desc' : '';
    }
  },
  watch: {
    commonProjectList: {
      handler(list) {
        this.calculateTotalAmount(list);
      },
      deep: true
    }
  },
  created() {
    if (!this.isEdit) this.queryTagTreeList();
  },
  methods: {
    editReimbursementTag,
    handleAdd() {
      this.$refs['dynamicEditTableRef'].addValue();
    },
    // 计算总报销金额
    calculateTotalAmount(list) {
      this.$nextTick(() => {
        let totalAmount = 0;
        list.forEach(item => {
          const amount = item.amount || 0;
          totalAmount += +amount;
        });
        this.$emit('change', totalAmount.toFixed(2));
      });
    },
    validateForm() {
      return new Promise((resolve, reject) => {
        this.$refs['dynamicEditTableRef'].validate().then(() => {
          resolve();
        }).catch(() => {
          reject();
        });
      });
    },
    extendEvent(data) {
      const extendData = data && data.scope && data.scope.row || {};
      this.$emit('extendEvent', extendData);
    },
    getTableData() {
      return this.commonProjectList;
    },
    setTableData(list) {
      if (Array.isArray(list) && list.length) {
        list.forEach(item => {
          const { amount } = item;
          if (amount || amount === 0) {
            item.amount = (+amount).toFixed(2);
          }
        });
      }
      this.commonProjectList = list;
    },
    // 获取所有标签
    queryTagTreeList() {
      const type = this.TAG_MODULES.PROCESS;
      getTagAll({ type }).then(res => {
        this.tagTreeList = (res && res.data) || [];
        this.tagTreeList.forEach(item => {
          if (!item.item) item.disabled = true;
        });
      });
    },
    handelClickEditTag(item, index) {
      this.editTagParams = { descId: item.id };
      this.$refs.editTagModuleRef.openDialog(item.tag);
    },
    editTagCallback() {
      this.editTagParams = {};
      this.$emit('freshData');
    }
  }
};
</script>

<style lang="scss" scoped>
.common-project-container {
  &::v-deep {
    .el-select {
      width: 100%;
    }
    .el-cascader--large {
      width: 100%;
    }
    .el-table__body td {
      background-color: #fff !important;
    }
  }
  .total-amount-price {
    display: flex;
    align-items: center;
    background-color: #f8f8f8;
    color: #999;
    font-size: 14px;
    font-weight: normal;
    margin-left: 10px;
    padding: 4px 6px;
    border-radius: 4px;
    > img {
      width: 14px;
      margin-right: 5px;
    }
    .price {
      font-size: 14px;
      color: #406eff;
      font-weight: bold;
    }
  }
  .options-btn-group {
    position: absolute;
    right: 0;
    display: flex;
    align-items: center;
  }
}
</style>
